package com.iamteer.day18.autoincrement;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.junit.Test;

public class App {
	private Connection con;
	private PreparedStatement pstmt;
	private ResultSet rs;
	
	private String url = "jdbc:mysql:///day18";
	private String user = "root";
	private String password = "123456";
	
	//1 插入数据，不获取自增长值
	@Test
	public void testGetAutoincrement1() {
		String sql = "INSERT INTO admin(username,password) VALUES(?,?)";
		
		try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection(url, user, password);
			
			pstmt = con.prepareStatement(sql);
			
			pstmt.setString(1, "chuck");
			pstmt.setString(2, "999");
			
			pstmt.executeUpdate();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally {
			try {
				if(pstmt != null){
					pstmt.close();
				}
				if(con != null){
					con.close();
				}
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
		
	}
	//2 插入数据，获取自增长值
	@Test
	public void testGetAutoincrement2() {
		String sql = "INSERT INTO admin(username,password) VALUES(?,?)";
		try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection(url, user, password);
			
			pstmt = con.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
			pstmt.setString(1, "chuck");
			pstmt.setString(2, "999");
			
			pstmt.executeUpdate();
			
			//在执行更新后，获取自增长列
			rs = pstmt.getGeneratedKeys();
			if (rs.next()) {
				System.out.println(rs.getInt(1));
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				rs.close();
				pstmt.close();
				con.close();
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		}
		
	}

	
	
	//保存员工同时保存部门测试
	@Test
	public void testSave() throws Exception{
		Dept dept = new Dept();
		dept.setDeptName("应用开发部");
		Employee employee = new Employee();
		employee.setEmpName("张三");
		employee.setDept(dept);
		
		EmpDao dao = new EmpDao();
		dao.save(employee);
	}
}
